#include "Animation.h"

// basic constructor
Animation::Animation() 
{
	m_index = 0;
	m_playing = false;
}

// make sure safer release is called
Animation::~Animation() {}

// setup the animation based on the appopriate spritesheet values
void Animation::initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, float fps, bool a_loop, bool relativeToCamera)
{
	// setup sprite sheet of animation
	SpriteSheet::initialize(fileName,count,numRows,numColumns,spriteWidth,spriteHeight, relativeToCamera);

	// set type to animation
	m_type = ANIMATION;

	m_playing = false;

	m_loop = a_loop;

	// calculate frames per second
	m_frameSwitch.initialize( (float)m_rects.size() / fps );
}

// update the animation timer 
void Animation::update(float dT)
{
	// if the animation is running update the frames
	if( m_playing )
	{
		// update timer
		m_frameSwitch.update(dT);

		// if the timer has finished then switch frames
		if( !m_frameSwitch.isActive() )
		{
			// if the end has been reached either loop or end animation
			if( m_index >= m_rects.size() - 1)
			{
				// loop the animation
				if( m_loop )
				{
					m_index = 0;
					m_frameSwitch.activate();
				}
				// end the animation
				else
				{
					m_frameSwitch.deActivate();
					m_playing = false;
				}
			}
			// animation has not reached the end
			else
			{
				m_index++;
				m_frameSwitch.activate();
			}
		}
	}
}

// set current frame and reset the timer
void Animation::setCurrentFrame(int index)
{
	// make sure the sprite exists
	if( setCurrentSprite(index) )
	{
		// reset frameswitch if it is currently running
		if(m_frameSwitch.isActive())
		{
			m_frameSwitch.deActivate();
			m_frameSwitch.activate();
		}
	}
}

// pause the animation at its current frame
void Animation::pause()
{
	m_playing = false;
}

// start the animation from its current frame
void Animation::play()
{
	m_playing = true;
	// start the timer
	m_frameSwitch.activate();
}

// reset to the first frame 
// pause afterwards if true
void Animation::reset(bool pause)
{
	// first reset to first frame
	m_index = 0;
	// reset the timer 
	m_frameSwitch.deActivate();

	if(pause)
	{
		// stop the animation
		m_playing = false;
	}
	else // otherwise re-activate the timer
		m_frameSwitch.activate();
}